package com.qingke.ocr.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/online")
public class OnlineServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public OnlineServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getSession().getAttribute("nick")==null){
			return ;
		}
		if(request.getSession().getAttribute("logged")==null||(Integer)request.getSession().getAttribute("logged")!=1){
			return ;
		}
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		ServletContext sc= getServletContext();
		if(sc.getAttribute("loginTimes")==null){
			sc.setAttribute("loginTimes", new HashMap<String,Long>());
		}
		@SuppressWarnings("unchecked")
		Map<String,Long> loginTimes=(Map<String,Long>)sc.getAttribute("loginTimes");
		
		String nick=request.getParameter("nickname");
		long time=(Long)request.getSession().getAttribute("loginTime");
		
		if(!loginTimes.containsKey(nick)){
			return ;
		}
		if((Long)loginTimes.get(nick).longValue()==time){
			return ;
		}
		request.getSession().removeAttribute("nick");
		request.getSession().removeAttribute("loginTime");
		request.getSession().removeAttribute("logged");
		
		response.getWriter().append("quit");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
